//引入模块
const express = require("express");
//引入上一级目录下的mysql的Query对象
const query = require("../util/query.js");
const {
	md5
} = require('../util/md5.js');
const JWT = require('../util/token.js');

//创建空路由器
let router = express.Router();
//==============================================
//用户模块 
//===============================================
//注册用户 POST /user/register
router.post("/register", async (req, res) => {
	try {
		//获取post请求的数据
		let user = req.body;
		//验证各项数据是否为空
		if (!user.name) throw new Error("用户名不能为空");
		if (!user.password) throw new Error("密码不能为空");
		if (!user.email) throw new Error("邮箱不能为空");
		//如果需要可以对其他数据进行验证....

		//生成盐（作料）,对明码密码进行密码MD5加密
		user.remark = user.password; //方便调试，密码明码暂放在备注字段
		user.salt = md5(Date.now().toString()); //生成盐（作料）
		user.password = md5(user.password + user.salt); //密码 = MD5(明码+盐)

		//创建sql并执行,将注册的数据插入到user数据表中
		let sql = "INSERT INTO xz_user SET ?";
		let result = await query(sql, [user]);
		if (result.affectedRows > 0) {
			let data = {
				user: {
					id: result.insertId,
					name: user.name
				}
			};
			return res.send({
				code: 1,
				msg: "注册成功",
				data
			});			
		}
		throw result;
	} catch (error) {
		res.send({
			code: -1,
			msg: error.message,
		});
	}
});

//===============================================
//登录用户  POST /user/login  返回携带token
router.post('/login', async (req, res) => {
	try {
		//获取数据
		let userLogin = req.body;
		//验证各项数据是否为空
		if (!userLogin.name) throw new Error("用户名不能为空");
		if (!userLogin.password) throw new Error("密码不能为空");

		//创建并执行SQL语句,查看是否有这样用户名的记录
		let sql = `SELECT id,name,password,salt FROM xz_user WHERE name ="${userLogin.name}"`;
		let result = await query(sql);
		//根据查询返回的结果集（result）长度是否大于0,判断是否有这个用户
		if (result.length > 0) { //有这个用户名的记录
			let user = result[0]; //获取记录中的用户id,name,password,salt
			//接下判断用户的密码是否正确，用户密码的形成参见用户注册代码
			if (user.password === md5(userLogin.password + user.salt)) {
				//密码正确,登陆成功后
				delete user.password; //删除不再需要的属性
				delete user.salt;
				//生成Token，并设置Token携带的信息
				let payload = {
					userId: user.id,
					userName: user.name,
				};
				//jwt--jsonwebtoken第三方库生成Token
				let token = JWT.sign(payload);
				return res.send({
					code: 1,
					msg: "登录成功",
					data: {
						user,
						token
					}
				});				
			}
		}
		throw new Error("用户名或密码错误");
	} catch (error) {
		res.send({
			code: -1,
			msg: error.message
		});
	}
});

// ========================================================
//验证用户是否已经登录接口 GET /user/isLogin 需要Token验证 
router.get("/isLogin", (req, res) => {
	//验证用户Token 请求头中携带Token  req.headers.authorization=
	let user = JWT.getUser(req, res);
	if (user == null) return;

	res.send({
		code: 1,
		msg: "已登录",
		data: {}
	});
});

//===============================================
//退出登录 GET /user/logout  //其实只要在客户端设置Token为空即可
router.get("/logout", (req, res) => {
  //可以在这里对用户的使用日志进行记录
	res.send({
		code: 1,
		msg: "登出成功"
	});
});

//========================================================
//检索用户 GET /user/detail
//参数 用户id
router.get("/detail", async (req, res) => {
	try {
		//获取get请求的数据
		let {
			id
		} = req.query;
		//验证各项数据是否为空
		if (!id) throw new Error("id不能为空");

		//执行SQL语句
		let sql = `SELECT id,name,email,phone,gender,avatar,nick_name FROM xz_user WHERE id=${id}`;
		let result = await query(sql);

		//如果数据查询成功，响应对象
		if (result.length > 0) {
			res.send({
				code: 1,
				msg: "成功",
				data: result[0], //返回的是数组第一个元素，是对象
			});
			return;
		}
		throw result;
	} catch (error) {
		res.send({
			code: -1,
			msg: error.message
		});
	}
});


//===============================================
//用户列表（分页） GET /user/page
//参数 pageIndex,	pageSize,keyword,orderBy
router.get("/page", async (req, res) => {
	//验证用户Token 请求头中携带Token  req.headers.authorization=
	let user = JWT.getUser(req, res);
	if (user == null) return;	
	
	//获取数据，如果页码pageIndex为空 默认为1 如果pageSize大小为空默认是10  要保证pageSize大小为整数
	//处理页码  
	let { pageIndex,pageSize,keyword, orderBy} = req.query;	
	keyword = keyword || "";	
	orderBy = orderBy || " id ";
	pageIndex = parseInt(pageIndex);
	pageIndex = pageIndex ? pageIndex : 1;
	//处理每页大小
	pageSize = parseInt(pageSize);
	pageSize = pageSize ? pageSize :  2147483647;  //10

	// 计算开始查询的值start
	let start = (pageIndex - 1) * pageSize;
	try {
		//执行2个SQL语句
		let sql = `SELECT count(*) as count FROM xz_user `;
		if(keyword) sql += ` WHERE name like '%${keyword}%' ` ;
		let result = await query(sql);
		let recordTotal = result[0]["count"]; //获取记录总数，返回记录集中只有1行数据
		let pageTotal = Math.floor(recordTotal / pageSize) + 1; //计算总页数 

		sql =	`SELECT id,name,email,phone,gender,avatar,nick_name FROM xz_user `;		
		if(keyword) sql += ` WHERE name like '%${keyword}%' ` ;
		if(orderBy) sql += ` ORDER BY ${orderBy} `
		sql += ` LIMIT ${start},${pageSize}`
		// console.log(sql)
		result = await query(sql);
		//如果数据获取成功（记录数量是0也是一种成功），响应对象
		return res.send({
			code: 1,
			msg: "成功",
			recordTotal, //总记录数
			pageIndex,  //页号
			pageSize, //每页大小
			pageTotal,  //总页数	
			data: result, //第2个SQL执行结果
		});		
	} catch (error) {
		res.send({
			code: -1,
			msg: error.message,
		});
	}
});


//===============================================
//修改用户	POST /user/update
//参数 参见user表
router.post("/update", async (req, res) => {
	//验证用户Token 请求头中携带Token  req.headers.authorization=
	let user = JWT.getUser(req, res);
	if (user == null) return;

	try {
		//获取数据
		let user = req.body;
		//验证各项数据是否为空  
		if (!user.id) throw new Error("用户Id不能为空");
		if (!user.name) throw new Error("用户名不能为空");
		if (!user.email) throw new Error("邮箱不能为空");
		if (!user.phone) throw new Error("电话不能为空");

		//创建并执行SQL语句 ，修改用户表中对应的数据
		let sql = `UPDATE xz_user SET ? WHERE id=${user.id}`;
		let result = await query(sql, [user]);

		//根据sql操作影响的记录行数，判断是否删除成功
		if (result.affectedRows > 0) {
			res.send({
				code: 1,
				msg: "更新成功！",
				data: {},
			});
			return;
		}
		throw {message:`用户编码(${user.id})记录不存在`};
	} catch (error) {
		res.send({
			code: -1,
			msg: error.message,
		});
	}
});

//===============================================
//修改密码 POST /user/updatepwd
//参数 id,password,password2
router.post("/updatepwd", async (req, res) => {
	//验证用户Token 请求头中携带Token  req.headers.authorization=
	let user = JWT.getUser(req, res);
	if (user == null) return;

	try {
		//获取数据
		let {
			id,
			password,
			password2
		} = req.body; //{id password newpwd}
		//验证各项数据是否为空  
		//console.log(req.body)
		if (!id) throw new Error("id不能为空!");
		if (!password) throw new Error("password不能为空!");
		if (!password2) throw new Error("password2不能为空!");

		//执行SQL语句,查看是否是否有这样的用户
		let sql = `SELECT password,salt FROM xz_user WHERE id = ${id}`;
		let result = await query(sql);

		//根据查询返回的结果集（result）长度是否大于0,判断是否有这个用户
		if (result.length > 0) {
			let user = result[0];
			if (user.password === md5(password + user.salt)) {
				//密码正确，继续
				password2 = md5(password2 + user.salt); // 对新的密码进行加密处理：密码=MD5(明码+盐)
				sql = `UPDATE xz_user SET password = "${password2}" WHERE id=${id}`;
				result = await query(sql);
				if (result.affectedRows > 0) {
					res.send({
						code: 1,
						msg: "密码修改成功",
						data: {}
					});
					return;
				}
			}
		}
		throw new Error("用户或密码错误"); // 进行错误处理，正确的已经return了
	} catch (error) {
		res.send({
			code: -1,
			msg: error.message
		});
	}
});

//=================================================================
//删除用户		GET /user/delete
//参数 用户Id
router.get("/delete", async (req, res) => {
	//验证用户Token 请求头中携带Token  req.headers.authorization=
	let user = JWT.getUser(req, res);
	if (user == null) return;

	// 验证通过，继续
	try {
		//获取数据
		let {
			id
		} = req.query;
		//验证数据		
		if (!id) throw new Error("id不能为空");

		//执行SQL语句，删除对应的数据
		let sql = `DELETE FROM xz_user WHERE id =${id}`;
		let result = await query(sql);
		//数据库操作影响的记录行数，判断是否删除成功
		if (result.affectedRows > 0) {
			res.send({
				code: 1,
				msg: "删除成功",
			});
			return;
		}
		throw {message:`用户编码(${id})记录不存在`};
	} catch (error) {
		res.send({
			code: -1,
			msg: error.message
		});
	}
});


//=================================================================
//重置用户密码		POST /user/resetPassword
//参数 用户Id、用户password
router.post("/resetPassword", async (req, res) => {
	//验证用户Token 请求头中携带Token  req.headers.authorization=
	let user = JWT.getUser(req, res);
	if (user == null) return;

	// 验证通过，继续
	try {
		//获取数据
		let {
			id,password
		} = req.body;
		//验证数据		
		if (!id) throw new Error("id不能为空");
		if (!password) throw new Error("password不能为空");

		//生成盐（作料）,对密码进行密码MD5加密
		let remark = password; //方便调试，密码明码暂放在备注字段
		let salt = md5(Date.now().toString()); //生成盐（作料）
		password = md5(password + salt); //密码 = MD5(明码+盐)
		
		let sql = `UPDATE xz_user SET password = "${password}",salt = "${salt}",remark = "${remark}" WHERE id=${id}`;
		result = await query(sql);
		if (result.affectedRows > 0) {
			res.send({
				code: 1,
				msg: "重置密码成功",
				data: {}
			});
			return;
		}
		throw new Error(`用户重置密码(${id})失败`);
	} catch (error) {
		res.send({
			code: -1,
			msg: error.message
		});
	}
});

// ========================================================
// 刷新Token  GET /user/tokenrefresh
router.get('/tokenrefresh', (req, res) => {
	//验证用户Token 请求头中携带Token  req.headers.authorization=
	let user = JWT.getUser(req, res);
	if (user == null) return;

	// 重新生成一个新的Token, 设置Token携带的信息，返回给前端
	let payload = {
		userId: user.id,
		userName: user.name
	};
	let token = JWT.sign(payload);
	res.send({
		code: 1,
		msg: '成功',
		data: {
			user,
			token,
		}
	});
});

//===============================================
//检测邮箱 (是否存在这样的邮箱）GET /user/checkemail
router.get("/checkemail", async(req, res) => {
  try {
    //获取数据
    let user = req.query;
    //验证数据    
		if (!user.email) throw new Error("邮箱不能为空");
    
    //创建并执行SQL语句
		let sql = `SELECT 1 FROM xz_user WHERE email ='${user.email}'`;
		let result = await query(sql);

    //数据库操作结果集的记录行数
    if (result.length > 0) {
      return res.send({
        code: -1,
        msg: `邮箱已存在 ${user.email}`,
      });
    }else{
      return res.send({
        code: 1,
        msg: `邮箱OK！ ${user.email}`,
      });
    }
  } catch (error) {
    res.send({
      code: -1,
      msg: error.message,
    });
  }
});

//===============================================
//检测手机 (是否存在这样的手机）GET /checkphone
router.get("/checkphone", async(req, res) => {
  try {
    //获取数据
    let user = req.query;
    //验证数据    
		if (!user.phone) throw new Error("手机号不能为空");
    
    //创建并执行SQL语句
		let sql = `SELECT 1 FROM xz_user WHERE phone ='${user.phone}'`;
		let result = await query(sql);

    //数据库操作结果集的记录行数
    if (result.length > 0) {
      return res.send({
        code: -1,
        msg: `手机号已存在 ${user.phone}`,
      });
    }else{
      return res.send({
        code: 1,
        msg: `手机号OK！ ${user.phone}`,
      });
    }
  } catch (error) {
    res.send({
      code: -1,
      msg: error.message,
    });
  }
});

//===============================================
//检测用户名 (是否存在这样的用户名）GET /checkname
router.get("/checkname", async(req, res) => {
  try {
    //获取数据
    let user = req.query;
    //验证数据    
		if (!user.name) throw new Error("用户名不能为空");
    
    //创建并执行SQL语句
		let sql = `SELECT 1 FROM xz_user WHERE name ='${user.name}'`;
		let result = await query(sql);

    //数据库操作结果集的记录行数
    if (result.length > 0) {
      return res.send({
        code: -1,
        msg: `用户名已存在 ${user.name}`,
      });
    }else{
      return res.send({
        code: 1,
        msg: `用户名OK！ ${user.name}`,
      });
    }
  } catch (error) {
    res.send({
      code: -1,
      msg: error.message,
    });
  }
});


// Admin 项目需要的接口，
//===============================================
//根据用户Token返回用户信息 POST /user/info
router.get("/info", async (req, res) => {	
	//验证用户Token 请求头中携带Token  req.headers.authorization=
	let user = JWT.getUser(req, res);
	if (user == null) return;
	
	// 验证通过，继续
	try {
		//执行SQL语句
		let sql = `SELECT id,name,email,phone,gender,avatar,nick_name FROM xz_user WHERE id=${user.id}`;
		let result = await query(sql);

		//如果数据查询成功，响应对象
		if (result.length > 0) {
			res.send({
				code: 1,
				msg: "成功",
				data: result[0], //返回的是数组第一个元素，是对象
			});
			return;
		}
		throw new Error("没有这样的用户");
	} catch (error) {
		res.send({
			code: -1,
			msg: error.message
		});
	}
});
//===============================================

//========================================================
//检索用户 GET /user/detail0  返回json字符串  
//参数 用户id
router.get("/detail0", async (req, res) => {
	try {
		//获取get请求的数据
		let {
			id
		} = req.query;
		//验证各项数据是否为空
		if (!id) throw new Error("id不能为空");

		//执行SQL语句
		let sql = `SELECT id,name,email,phone,gender,avatar,nick_name FROM xz_user WHERE id=${id}`;
		let result = await query(sql);

		let ret="";
		//如果数据查询成功，响应对象
		if (result.length > 0) {
			ret = JSON.stringify(result[0]);			
		}
		res.send(ret);
	} catch (error) {
		res.send("");
	}
});




//导出路由器
module.exports = router;